

import requests
from bs4 import BeautifulSoup

class AudioFiles:
    def __init__(self,url):
        self.url=url
        self.mainTitle=''
        self.audios=[]

    def getHtml(self):
        # 醴梓厙珜URL
        # url = 'https://www.pep.com.cn/zslth/yyptypzj/xypep/3s/'
        url = self.url
        
        # 楷冞HTTP
        response = requests.get(url)
        
        # 潰脤岆瘁傖髡
        if response.status_code == 200:
            # 妏蚚BeautifulSoup賤昴厙珜囀
            soup = BeautifulSoup(response.text, 'html.parser')
            list_=soup.find_all('div', class_='container_title_typtzy2024')
            self.mainTitle=list_[0].find('h3').text.strip()

            list_=soup.find_all('div', class_='container_title_ptptzy2024')
            # 取得课文標題
            titles=[]
            for item in list_:
                title=item.find('span').text.strip()
                titles.append(title)
            
            # print(titles)

            list_=soup.find_all('div', class_='container_list_ptptzy2024')
            audios=[]
            for i,s in enumerate(list_) :
                audio={'title':titles[i],'audios':self.getaudio(s)}
                audios.append(audio)
            # print(audios[0])
            self.audios=audios

        else:
            print('Failed to retrieve the webpage')

    def getaudio(self,soup: BeautifulSoup):
        names=soup.find_all('h5')
        tags=soup.find_all('audio', class_='col-xs-12 col-sm-12 col-md-6 col-lg-6')
        src_values = [{'name':names[i].text.strip(),'src':tag['src']} for i,tag in enumerate(tags)  if 'src' in tag.attrs]
        return src_values



if __name__ == '__main__':
    url = 'https://www.pep.com.cn/zslth/yyptypzj/xypep/3s/'
    af=AudioFiles(url)
    af.getHtml()
